package com.xingdata.jjxc.utils;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 
 * 
 * 项目名称：JJXC_VPN 类名称：ThreadPoolManager 类描述： 线程池管理工具
 * 不要每次都开启一个新线程去访问服务器，新建一个线程的代价比从线程池中取一个线程的代价要高 创建人：JiangMin 创建时间：2015-6-19
 * 下午6:40:15 修改备注：
 * 
 * @version
 * 
 */

public class ThreadPoolManager {
	private ExecutorService service;
	// 线程池维护线程的最少数量
	private static int DEFAULT_COREPOOLSIZE = 5;
	// 线程池维护线程的最大数量
	private static int DEFAULT_MAXIMUM_POOLSIZE = 15;
	// 线程池维护线程所允许的空闲时间
	private static long DEFAULT_KEEP_ALIVE_TIME = 30;
	// 线程池所使用的缓冲队列
	private BlockingQueue<Runnable> bq;

	private ThreadPoolManager() {
		bq = new ArrayBlockingQueue<Runnable>(DEFAULT_COREPOOLSIZE);

		service = new ThreadPoolExecutor(DEFAULT_COREPOOLSIZE,
				DEFAULT_MAXIMUM_POOLSIZE, DEFAULT_KEEP_ALIVE_TIME,
				TimeUnit.SECONDS, bq);
	}

	private static ThreadPoolManager manager = new ThreadPoolManager();

	public static ThreadPoolManager getInstance() {
		if (manager == null) {
			manager = new ThreadPoolManager();
		}
		return manager;
	}

	public void addTask(Runnable runnable) {
		try {
			service.execute(runnable);
		} catch (RejectedExecutionException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 退出的时候关闭线程池
	 */
	public void shutdown() {
		if (service != null) {
			service.shutdown();
			service = null;
			manager = null;
		}
	}
}
